import React, { forwardRef, memo, useImperativeHandle, useRef } from 'react'

const HelloWorld = memo(
  forwardRef(function (props, ref) {
    const inputRef = useRef()

    // 暴露父组件传入的ref功能
    useImperativeHandle(ref, () => {
      return {
        focus() {
          console.log('focus')
          inputRef.current.focus()
        },
        setValue(value) {
          inputRef.current.value = value
        },
      }
    })

    return <input type="text" ref={inputRef} />
  })
)

export default memo(function App() {
  const titleRef = useRef()
  const inputRef = useRef()

  function handleDOM() {
    console.log(titleRef.current)
    console.log(inputRef.current)
    inputRef.current.focus()
    inputRef.current.setValue('')
  }

  return (
    <div>
      <h2 ref={titleRef}>哈哈哈</h2>
      <HelloWorld ref={inputRef} />
      <button onClick={handleDOM}>DOM操作</button>
    </div>
  )
})
